/**
 * author:Administrator
 * date:2016/1/5
 * desc:TODO
 */
'use strict';

var assert = require('assert');
var request = require('request');

var resetDone;
var totalQty = 5;
var extraCnt = 2;


function waitResetDone(done) {
  if (!!resetDone)done();
  else setTimeout(function () {
    waitResetDone(done);
  }, 500);
}

describe('transaction', function () {
  var resetUrl = 'http://localhost:9990/reset?qty=%qty'.replace('%qty', totalQty);
  it('reset', function (done) {
    request(resetUrl, function (err, res, data) {
      assert.equal(null, err);
      resetDone = 1;
      done();
    });
  });
});


describe('transaction', function () {
  this.timeout(5000);
  before(function (done) {
    waitResetDone(done);
  });

  var msg = 'totalQty=%totalQty, extraCnt=%extraCnt'
    .replace('%totalQty', totalQty)
    .replace('%extraCnt', extraCnt);
  it(msg, function (done) {
    var opt = {
      uri: 'http://localhost:9990/coupon/application',
      method: 'POST',
      json: {
        "cvid": 1001,
        "uid": 100,
        "qty": 1,
        "cond": "aa"
      }
    };
    var reqCnt = totalQty + extraCnt,
      resCnt = 0,
      i = 0,
      rollbackCnt = 0;
    for (i = 0; i < reqCnt; i++) {
      request(opt, function (err, res, data) {
        assert.equal(null, err);
        resCnt++;
        if (data.errcode != 0) {
          rollbackCnt++;
        }
        if (resCnt == reqCnt) {
          assert.equal(rollbackCnt, extraCnt);
          done();
        }
      });
    }
  });
});